<template>
  <div id="login">

    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
      <el-form :model="loginForm" :rules="rules" class="login-container" size="medium" @keydown.enter="handleClick">
        <h3 class="login_title">用户登录</h3>
        <el-form-item prop="currentRole">
          <el-col :span="8" align="center">
            <el-button :class="{ 'selected-role': currentRole === 0 }" @click="checkRole(0)">游客</el-button>
          </el-col>
          <el-col :span="8" align="center">
            <el-button :class="{ 'selected-role': currentRole === 2 }" @click="checkRole(2)">酒店管理员</el-button>
          </el-col>
          <el-col :span="8" align="center">
            <el-button :class="{ 'selected-role': currentRole === 1 }" @click="checkRole(1)">系统管理员</el-button>
          </el-col>
        </el-form-item>
        <el-form-item prop="username">
          <el-input type="text" v-model="loginForm.username" autofocus ref="username" auto-complete="off"
            placeholder="用户名/邮箱" spellcheck="false">
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" v-model="loginForm.password" autofocus ref="password" auto-complete="off"
            placeholder="密码" v-on:input="change">
          </el-input>
        </el-form-item>
        <el-form-item style="width: 100%;">
          <el-checkbox class="login_remember" v-model="checked">
            <span style="color: #409EFF">记住我</span>
            <label style="color: #949493;text-align: right;">不是自己电脑请勿勾选</label>
          </el-checkbox>
          <el-button type="text" style="float: right; text-decoration: none; color: #50b6ff"
            @click="beforeTo">找回密码？</el-button>
        </el-form-item>
        <el-form-item style="width: 100%">
          <el-button type="primary" class="button_login" style="margin-right: 20px;" @click="onLoginClick">登录</el-button>
          <!-- <router-link to="register">
                  </router-link> -->
          <!-- <router-link to="signUp"> -->
          <el-button type="primary" class="button_register" @click="toRegisterPage">注册</el-button>
          <!-- </router-link> -->

        </el-form-item>
        <el-row>
          <el-col>
            <p>测试账号：</p>
            <p>游客：（账号:shuqiyue120 密码:shuqiyue120）</p>
            <p>酒店管理员：(账号:suliu666 密码:suliu666)</p>
            <p>系统管理员：(账号:suliu999 密码:suliu999)</p>
          </el-col>
        </el-row>
      </el-form>
    </el-col>
    <p class="login-copyright">© {{ currentYear }} cf 版权所有</p>
  </div>
</template>

<script>
import { postRequestWithRaw } from "../api/axiosRequest";
export default {
  name: 'Login',
  data() {
    return {
      rules: {
        username: [{ required: true, message: '用户名或邮箱不能为空', trigger: 'change' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'change' }]
      },
      checked: false,
      loginForm: {
        username: '',
        password: '',
      },
      msg: null,
      currentRole: 0, // 初始状态为空
      isInput: false,
      currentYear: new Date().getFullYear(),
    }
  },
  methods: {
    // mounted() {
    //   // 页面加载完成后设置currentRole为0，以便选中第一个按钮
    //   this.loginForm.currentRole = 0
    // },
    toRegisterPage() {
      this.$router.push('/signUp')
    },
    checkRole(roleId) {
      this.currentRole = roleId;
      console.log(roleId)
    },

    async onLoginClick() {
      // 获取表单数据
      const form = this.loginForm;
      const keys = Object.keys(form);

      console.log(form);
      console.log(keys);

      keys.forEach(key => {
        if (!form[key]) {
          this.isValid = false;
          this.checked = false;
        } else if (form[key]) {
          this.isValid = true;
          // this.checked = true;
        }
      });


      if (this.isValid && this.checked) {
        try {
          const result = await postRequestWithRaw("/user/checkLogin", {
            username: this.loginForm.username,
            password: this.loginForm.password,
            role: this.currentRole
          });

          console.log("result:" + result);

          if (result.status === 200) {
            const data = result.data
            if (data.status === 1) {
              console.log(data.data);
              let userInfo = data.data
              localStorage.setItem("userId", userInfo.userId)
              localStorage.setItem("role", userInfo.role)
              localStorage.setItem("token", userInfo.token)
              localStorage.setItem("expirationTime", userInfo.expirationTime)
              this.msg = "登录成功"
              if (userInfo.role === 0) {
                this.$router.push("/traveler")
              } else if (userInfo.role === 1) {
                this.$router.push("/manager")
              } else if (userInfo.role === 2) {
                this.$router.push('/hotelmanager')
              } else {
                this.$router.push('/login')
              }
              ElNotification({
                title: '登录提示',
                message: this.msg,
                type: 'success',
              })
            } else {
              this.msg = result.data.msg
              ElNotification({
                title: '登录提示',
                message: this.msg,
                type: 'success',
              })
            }
          } else {
            console.log("Network Error");
          }
        } catch (error) {
          console.log(error);
        } finally {
          console.log("finally");
        }
      } else {
        console.log(this.checked);
        if (this.checked === false) {
          ElNotification({
            title: '登录提示',
            message: "请勾选约束条款",
            type: 'success',
          })
          return;
        }
        ElNotification({
          title: '登录提示',
          message: '请完成表单输入',
          type: 'warning',
          duration: 3000,
        });
        return;
      }
      // 2594359181@qq.com

    },
    change() {
      // 如果监听到输入框发生变化，那么采用用户输入的密码
      this.isInput = true;
    },
    beforeTo() {
      if (this.loginForm.username === '') {
        console.log(111)
        ElNotification({
          title: '跳转失败',
          message: "输入用户名或邮箱再去重置密码吧",
          type: 'error'
        })
      } else {
        this.$router.push({
          name: 'resetPassword',
          query: {
            username: this.loginForm.username,
          }
        })
      }
    },

  }


}
</script>

<style scoped>
#login {
  background-image: url('/src/assets/image/loginPage/login_back.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  height: 100%;
  width: 100%;
  position: fixed;
}

.login-container {
  border-radius: 15px;
  background-clip: padding-box;
  margin: 40px auto;
  width: 30%;
  padding: 25px 30px;
  background: #fff;
  border: 1px solid #eaeaea;
  box-shadow: 0 0 25px #cac6c6;
  opacity: 0.7;

  /* 媒体查询，根据屏幕宽度改变样式 */
  @media screen and (max-width: 1200px) {
    width: 70%;
    margin: 40px auto;
  }

  /* 媒体查询，根据屏幕宽度改变样式 */
  @media screen and (max-width: 768px) {
    width: 70%;
    margin: 40px auto;
  }

  @media screen and (max-width: 480px) {
    width: 70%;
    margin: 40px auto;

  }
}

.selected-role {
  background-color: #409EFF;
  color: white;
}

.login_title {
  margin: 0px auto 40px auto;
  text-align: center;
  color: #505458;
}

.login_remember {
  margin: 0px;
  text-align: left;
  float: left;

}

.button_login {
  width: 40%;
  background: #409EFF;
  border: none;
  float: left
}

.button_register {
  width: 40%;
  background: #505458;
  border: none;
  float: right;
}

.login-copyright {
  color: #505458;
  padding-bottom: 20px;
  text-align: center;
  position: relative;
  z-index: 1;
}

@media screen and (min-height: 550px) {
  .login-copyright {
    position: absolute;
    bottom: 0;
    right: 0;
    left: 0;
  }
}
</style>